﻿
var EzUserInfoSelector = function (dialogCloseCallback) {
    this._dialogCloseCallback = dialogCloseCallback;

    this._init();
}

EzUserInfoSelector.prototype = {
    URL_GetAllUserInfo: "http://localhost:19245/core/GetAllUserInfo",

    _pinyin: new Pinyin(),

    //<div id="ezdesk_chooseUsers" >
    //    <div id="ez-chooseuser-userinfo-detail-choose">
    //        <p style="overflow: hidden; background-color: #F0F5F8; padding: 2px 5px; margin-bottom: 2px;">
    //            <span style="float: left">请选择员工</span>
    //             <span style="float: right">
    //                <select id="dept_select"></select>
    //             </span>
    //         </p>
    //         <div id="ez-chooseuser-userinfo-detail-data-holder">
    //         </div>
    //         <div style="float: right; padding: 2px 5px;">
    //            <input id="btnSelectNewUserInfos" type="button" value="确定"/>
    //         </div>
    //    </div>
    //    <div id="ez-chooseuser-pnlChoose" >
    //        <input type="text" id="txtNames"/>
    //        <span id="ez-chooseuser-btn-detail-choose"></span>
    //    </div>
    //    <h3 style="margin: 2px 5px;">已经选中的员工：</h3>
    //    <div id="ez-chooseuser-userinfo-selected-holder">
    //    </div>
    //</div>

    _thisDialogs: $('<div id="ezdesk-chooseUsers" >    <div id="ez-chooseuser-userinfo-detail-choose">        <p style="overflow: hidden; background-color: #F0F5F8; padding: 2px 2px; margin-bottom: 2px;">            <span style="float: left">请选择员工</span>             <span style="float: right">                <select id="dept_select"></select>             </span>         </p>         <div id="ez-chooseuser-userinfo-detail-data-holder">         </div>         <div style="float: right; padding: 2px 5px;">            <input id="btnSelectNewUserInfos" type="button" value="选择"/>         </div>    </div>    <div id="ez-chooseuser-pnlChoose" >        <input type="text" id="txtNames"/>        <span id="ez-chooseuser-btn-detail-choose"></span>    </div>    <h3 style="margin:10px 2px  0 2px;">已经选中的员工：</h3>    <div id="ez-chooseuser-userinfo-selected-holder">    </div></div>'),

    _allUserInfoData: null,
    _allUserInfoDataStorage: null,


    _selectedUserInfo: null,  // 已经选择的公司员工数据

    _originalText: "输入要选择的员工姓名...",

    _dialogCloseCallback: null,

    b_showUserInfoChoose: false,

    initialize: function () {

    },

    showUserInfoDetailChoose: function (subWindowTop, subWindowLeft) {
        this.b_showUserInfoChoose = true;
        $('#ez-chooseuser-userinfo-detail-choose').css({
            top: subWindowTop,
            left: subWindowLeft
        });
        $('#ez-chooseuser-btn-detail-choose')
            .removeClass('ui-icon ui-icon-carat-1-s')
            .addClass('ui-icon ui-icon-carat-1-n');

        $('#dept_select').val("所有部门");
        this.bindUserInfoDetailData();
    },

    hideUserInfoDetailChoose: function () {
        $('#ez-chooseuser-userinfo-detail-choose').css({
            top: '-9999px',
            left: '-9999px'
        });
        this.b_showUserInfoChoose = false;
        $('#ez-chooseuser-btn-detail-choose')
            .removeClass('ui-icon ui-icon-carat-1-n')
            .addClass('ui-icon ui-icon-carat-1-s');
    },

    selectedUserInfo: function (name) {
        var _self = this;
        $(this._allUserInfoData).each(function (index, item) {
            if (item.Name == name && !item.IsSelected) {
                _self.renderNewSelectedUserInfo(item);
                item.IsSelected = true;
            }
        });
    },

    removeSelectedUserInfo: function (name) {
        $(this._allUserInfoData).each(function (index, item) {
            if (item.Name == name && item.IsSelected) {
                item.IsSelected = false;
            }
        });
    },

    renderNewSelectedUserInfo: function (item) {
        var _self = this;
        var selectedUserInfo = $('<span class="ez-chooseuser-lblSelectedUserInfo"></span>')
              .append(item.Name)
              .append($('<span class="ez-chooseuser-btnDeleteUserInfo"/>'))
              .val(item.Name);

        selectedUserInfo
            .find('.ez-chooseuser-btnDeleteUserInfo')
            .addClass('ui-icon ui-icon-close')
            .hover(function () {
                $(this)
                .addClass('ui-icon-closethick')
                .parent('.ez-chooseuser-lblSelectedUserInfo').addClass('ui-state-hover');

            }, function () {
                $(this)
                .removeClass('ui-icon-closethick')
                .parent('.ez-chooseuser-lblSelectedUserInfo').removeClass('ui-state-hover');
            })
            .css({
                display: 'inline-block'
            })
            .click(function () {
                var label = $(this).parent('.ez-chooseuser-lblSelectedUserInfo');
                _self.removeSelectedUserInfo(label.val());
                label.remove();
            });
        selectedUserInfo.appendTo('#ez-chooseuser-userinfo-selected-holder');
    },

    renderUserInfoDetail: function (targetUserinfoList) {
        var dataContainer = $('#ez-chooseuser-userinfo-detail-data-holder').empty();
        var ulContainer = $('<ul/>');
        var listContainer = $('<li/>');
        var i = 0;
        $(targetUserinfoList).each(function (index, item) {

            if (!item.IsHide) {
                var labelUser = $('<label for="' + item.Id + '"/>')
                      .append(
                        $('<input type="checkbox" id="' + item.Id + '" />')
                          .val(item.Name)
                        )
                      .append(item.Name);
                if (item.IsSelected) {
                    $('input:checkbox', labelUser).attr('checked', 'checked');
                    $('input:checkbox', labelUser).attr('disabled', 'true');
                }
                labelUser.appendTo(listContainer);
                i++;
                if (i % 4 == 0) {
                    listContainer
                        .append('<div style="clear: both;"></div>')
                        .appendTo(ulContainer);
                    listContainer = $('<li/>');
                }
            }
        });

        // 每四个换行 
        if (i % 4 != 0) {
            listContainer
                .append('<div class="clear-both"></div>')
                .appendTo(ulContainer);
        }

        dataContainer.append(ulContainer);
    },

    updateUserInfoDetailData: function () {
        var _self = this;
        $('#ez-chooseuser-userinfo-selected-holder').empty();
        $(this._allUserInfoData).each(function (index, item) {
            if (item.IsSelected) {
                _self.renderNewSelectedUserInfo(item);
                item.IsSelected = true;
            }
        });
    },



    bindUserInfoDetailData: function (deptName) {
        // 没有数据，直接退出
        if (!this._allUserInfoData) {
            return;
        }

        if (deptName == '所有部门') {
            deptName = null;
        }

        var targetUserinfoList = this._allUserInfoData;

        //筛选部门
        $(targetUserinfoList).each(function (index, item) {
            if (deptName != null && item.Dept.DeptName != deptName) {
                item.IsHide = true;
            } else {
                item.IsHide = false;
            }
        });

        this.renderUserInfoDetail(targetUserinfoList);
    },

    bindUserInfoDetailDeptList: function () {
        var _self = this;
        // 绑定所有部门
        //先把所有部门找出来
        var deptList = [];
        $(this._allUserInfoDataStorage).each(function (index, item) {
            var isContained = false;
            $(deptList).each(function (index, existedItem) {
                if (existedItem['text'] == item.Dept.DeptName) {
                    isContained = true;
                }
            });
            if (!isContained) {
                var newItem = new Object();
                newItem.text = item.Dept.DeptName;
                newItem.value = item.Dept.DeptName;
                deptList[deptList.length] = newItem;
            }
        });
        $('#dept_select').change(function (e) {
            _self.bindUserInfoDetailData(e.target.value);
        });
        $('#dept_select').comboxBindingWithEmptyDefault(deptList, 'text', 'value', "所有部门");
    },

    initializeData: function () {
        var _self = this;

        var resultCallback = function (result) {
            // 添加 拼音 字段
            $(result).each(function (index, item) {
                item.Pinyin = _self._pinyin.getFullChars(item.Name).toLowerCase() + _self._pinyin.getCamelChars(item.Name).toLowerCase();
            });
            _self._allUserInfoDataStorage = result;
            _self.bindUserInfoDetailDeptList();
        };

        if (ezmock.IS_MOCKED) {
            resultCallback(ezmock.URL_GetAllUserInfo);
        } else {
            $.getJSON(this.URL_GetAllUserInfo, null, resultCallback);
        }
    },


    _init: function () {
        var _self = this;

        _self._thisDialogs
          .prependTo("body")
          .hide();

        _self.initializeData();

        $('#txtNames')
        .val(_self._originalText)
        .css({
            color: '#aaa',
            width: '230px'
        });

        $('#txtNames').autocomplete({
            delay: 0,
            minLength: 0,
            source: function (req, add) {
                if (!_self._allUserInfoData) {
                    return;
                }

                var keyWord = req.term.toLowerCase();

                // 在 当前可供选择的员工数据中，将包含这个字符串的找出来
                var suggestions = [];

                $(_self._allUserInfoData).each(function (index, item) {
                    // 最多显示10个记录
                    if (suggestions.length >= 10) {
                        return;
                    }
                    if (!item.IsSelected && (item.Name.indexOf(keyWord) >= 0 || item.Pinyin.indexOf(keyWord) >= 0)) {
                        var newItem = new Object();
                        newItem.label = item.Name + '  (' + item.Dept.DeptName + ')';
                        newItem.value = item.Name;
                        suggestions[suggestions.length] = newItem;
                    }
                });

                add(suggestions);
            }
        })
        .bind("autocompleteselect", function (event, ui) {
            _self.selectedUserInfo(ui.item.value);
        });

        $('#ez-chooseuser-btn-detail-choose')
          .addClass('ui-icon ui-icon-carat-1-s');
        
        //end of initialize


        //binding events
        $('#txtNames').focusin(function () {
            $(this)
                .val('')
                .css({
                    color: '#000'
                })
        });

        $('#txtNames').focusout(function () {
            $(this)
            .val(_self._originalText)
            .css({
                color: '#aaa'
            });
        });


        $('#ez-chooseuser-userinfo-detail-choose').click(function (e) {
            e.stopPropagation();
        });
        $(document).click(function () {

            // 关闭选择用户框 
            if (_self.b_showUserInfoChoose) {
                _self.hideUserInfoDetailChoose();
            }
        });

        $('#ez-chooseuser-btn-detail-choose').click(function (e) {
            if (_self.b_showUserInfoChoose) {
                _self.hideUserInfoDetailChoose();
            }
            else {
                var thisBtn = this;
                var subWindowLeft = '3px';
                var subWindowTop = thisBtn.offsetTop + thisBtn.clientHeight + 2;

                _self.showUserInfoDetailChoose(subWindowTop, subWindowLeft);

                e.stopPropagation();
            }
        });

        $('#btnSelectNewUserInfos').click(function () {
            // 寻找所有 disable = false check = true的checkBox，这些就是新选择的UserInfo
            $('#ez-chooseuser-userinfo-detail-data-holder input:checkbox').each(function (index, item) {
                if ($(item).attr('checked') && !$(item).attr('disabled')) {
                    var name = $(item).val();
                    _self.selectedUserInfo(name);
                }
            });

            _self.hideUserInfoDetailChoose();
        });

        //end of binding events

    },
    getSelectedInfos: function () {
        var _self = this;
        var selectedPersons = [];
        $(_self._allUserInfoData).each(function (index, item) {
            if (item.IsSelected) {
                selectedPersons[selectedPersons.length] = item;
            }
        });

        return selectedPersons;
    },

    cloneJson: function (jsonObj) {
        var _self = this;
        var buf;
        if (jsonObj instanceof Array) {
            buf = [];
            var i = jsonObj.length;
            while (i--) {
                buf[i] = _self.cloneJson(jsonObj[i]);
            }
            return buf;
        } else if (jsonObj instanceof Object) {
            buf = {};
            for (var k in jsonObj) {
                buf[k] = _self.cloneJson(jsonObj[k]);
            }
            return buf;
        } else {
            return jsonObj;
        }
    },

    Show: function () {
        var _self = this;
        if (!_self._allUserInfoDataStorage) {
            return false;
        }
        _self._allUserInfoData = _self.cloneJson(_self._allUserInfoDataStorage);
        _self.updateUserInfoDetailData();
        _self._thisDialogs.dialog({
            modal: true,
            title: '选择员工',
            height: 308,
            width: 400,
            resizable: false,
            buttons: {
                "确定": function () {
                    var selectedUserInfos = _self.getSelectedInfos();
                    _self._dialogCloseCallback(selectedUserInfos);
                    _self._allUserInfoDataStorage = _self.cloneJson(_self._allUserInfoData);
                    $(this).dialog("close");
                }
            }
        });


    }

};
